using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using DesktopApp.ViewModels;
using DesktopApp.ViewModels.Services;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace DesktopApp;

public partial class App : Application
{
    /// <summary>
    /// Gets the current <see cref="App"/> instance in use
    /// </summary>
    public new static App Current => (App)Application.Current!;

    /// <summary>
    /// Gets the <see cref="IServiceProvider"/> instance to resolve application services.
    /// </summary>
    public IServiceProvider? Services { get; private set; }

    public override void Initialize()
    {
        AvaloniaXamlLoader.Load(this);
    }

    public override void OnFrameworkInitializationCompleted()
    {
        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            var services = new ServiceCollection();
            ConfigureServices(services);
            Services = services.BuildServiceProvider();

            // Resolve and show the main window
            desktop.MainWindow = Services.GetRequiredService<MainWindow>();
            // Optionally resolve the ViewModel here too if not injected into MainWindow
            // desktop.MainWindow.DataContext = Services.GetRequiredService<MainWindowViewModel>();

            desktop.MainWindow.Show();
        }

        base.OnFrameworkInitializationCompleted();
    }

    /// <summary>
    /// Configures the services for the application.
    /// </summary>
    private void ConfigureServices(IServiceCollection services)
    {
        // Register Services (Using Singleton for simplicity in this app)
        services.AddSingleton<ILogFileService, LogFileService>();
        services.AddSingleton<ILogProcessingService, LogProcessingService>();
        services.AddSingleton<IStatisticsService, StatisticsService>();
        
        // UIService and RuleManagementService might need the main window later.
        // Instead of Func<Window?>, we inject IServiceProvider and resolve MainWindow when needed.
        services.AddSingleton<IUIService, UIService>();
        services.AddSingleton<IRuleManagementService, RuleManagementService>();

        // Register ViewModels (Singleton for MainWindowViewModel is often ok for main window)
        services.AddSingleton<MainWindowViewModel>();
        // Other ViewModels like RuleEditorViewModel should likely be Transient if needed via DI
        // services.AddTransient<RuleEditorViewModel>(); 

        // Register MainWindow itself
        services.AddSingleton<MainWindow>();
    }
}